#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/9/6 11:11
# @File           : __init__
# @IDE            : PyCharm
# @desc           : 描述

from typing import Any, Coroutine, List
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm.strategy_options import _AbstractLoad
from core.crud import DalBase
from . import models, schemas
from apps.check.female.crud import QARFemaleDal
from apps.check import QAR
from core.exception import CustomException


class PlanDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(PlanDal, self).__init__()
        self.db = db
        self.model = models.DCPlan
        self.schema = schemas.PlanSimpleOut

    # async def create_data(self, data, v_options: List[_AbstractLoad] = None, v_return_obj: bool = False, v_schema: Any = None) -> Coroutine[Any, Any, Any]:
    #     # unique = self.get_data(part_no=data.part_no, v_return_none=True)
    #     # if unique:
    #     #     return unique
    #     return await super().create_data(data, v_options, v_return_obj, v_schema)

    async def put_data(self, data_id: int, data):
        plan = await self.get_data(data_id=data_id)
        msg = None
        if plan.plan_type == "母本异常":
            # 检查母本异常是否处理
            obj = await QARFemaleDal(self.db).get_datas(part_no=plan.part_no)
            if not obj:
                msg = "待办未处理，请先处理后再点击确认：母本不存在"
            else:
                obj = await QAR.crud.QARDal(self.db).get_datas(part_no=plan.part_no, purchase_order=plan.form_no)
                if not obj:
                    msg = "待办未处理，请先处理后再点击确认：未生成QAR"

        elif plan.plan_type == "驳回":
            # 检查驳回异常是否处理
            pass

        if msg:
            raise CustomException(msg=msg)
        
        plan.update_user = data.update_user
        plan.status = "已处理"

        await self.flush(plan)
        return self.schema.model_validate(plan).model_dump()
        